package com.example.nacos.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class DatasourceConfig {

    @Value("${spring.datasource.dynamic.datasource.slave1.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.dynamic.datasource.slave1.url}")
    private String url;

    @Value("${spring.datasource.dynamic.datasource.slave1.username}")
    private String username;

    @Value("${spring.datasource.dynamic.datasource.slave1.password}")
    private String password;
    @Value("${spring.datasource.dynamic.datasource.slave1.druid.initial-size}")
    private Integer initialSize;

    @Value("${spring.datasource.dynamic.datasource.slave1.druid.max-active}")
    private Integer maxActive;

    @Value("${spring.datasource.dynamic.datasource.slave1.druid.min-idle}")
    private Integer minIdle;
    @Value("${spring.datasource.dynamic.datasource.slave1.druid.min-wait:3000}")
    private Integer maxWait;
    @Value("${spring.datasource.dynamic.datasource.slave1.druid.time-between:60000}")
    private Integer timeBetweenEvictionRunsMillis;

    @Bean
    public DruidDataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();

        // 配置数据库连接参数
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        // 配置连接池参数
        dataSource.setInitialSize(initialSize);      // 初始连接数
        dataSource.setMaxActive(maxActive);      // 最大连接数
        dataSource.setMaxWait(maxWait);      // 获取连接最大等待时间(毫秒)
        dataSource.setMinIdle(minIdle);         // 最小空闲连接数
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); // 检测间隔
        return dataSource;
    }

}
